Repository navigation
[PyT] Add per-sequence attention policies to packed THD attention - #3274
Conversation
| @pytest.mark.parametrize( | ||
| "sequence_is_causal", | ||
| ( | ||
| (False, True, False, True), |
There was a problem hiding this comment.
The PyTorch QA job explicitly enumerates attention test modules and does not include this new file, so its forward, gradient, validation, and empty-batch coverage never runs in CI and regressions in the new dispatch path go undetected.
Knowledge Base Used: Tests and QA
Greptile SummaryThe PR adds per-sequence attention policies for packed THD attention and exposes policy dispatch through DotProductAttention, MultiheadAttention, and TransformerLayer.
Confidence Score: 5/5The PR appears safe to merge because no blocking failure remains. No blocking failure remains. Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
TL[TransformerLayer] --> MHA[MultiheadAttention]
MHA --> DPA[DotProductAttention]
DPA --> V[Validate per-sequence policies]
V --> D{Dispatch mode}
D -->|grouped| G[Compact policy tokens]
D -->|auto| B{Backend supports padding representation?}
B -->|yes| P[Preserve packed storage and mask inactive lanes]
B -->|no| G
P --> C[Combine policy outputs]
G --> C
Reviews (18): Last reviewed commit: "Merge branch 'main' into desh/mixed-thd-..." | Re-trigger Greptile |
Signed-off-by: Desh Raj <r.desh26@gmail.com>
Signed-off-by: Desh Raj <r.desh26@gmail.com>
Replace the per-policy Q/K/V gather and output scatter dispatcher with the review-suggested inter-sequence-padding design. Keep the original packed Q/K/V storage, derive logical and physical cu-seqlens for each mask policy, run the ordinary scalar-mask DPA path with pad_between_seqs, and sum its disjoint zero-padded outputs. Expose a generic attn_mask_type_per_seq mapping plus window_size_per_mask_type so callers can combine full-context offline attention with bounded causal attention. Preserve the scalar fast path for uniform batches, avoid policy-dependent host synchronization, and cover forward/backward parity, existing physical padding, cross-attention, per-policy windows, bottom-right masks, invalid inputs, empty batches, and CUDA graph replay. NRT H100 validation passed all 16 TransformerEngine cases and 3 focused Megatron integration tests. In an 8-node/64-H100 matched-auto comparison over iterations 7-100, grouped averaged 1802.289 ms and pad-between averaged 1779.596 ms (-1.259%); the paired 95% interval crossed zero, indicating practical parity when the backend is held constant. In the deployable-backend comparison, grouped/Flash averaged 1596.129 ms while pad-between/auto-cuDNN averaged 1766.769 ms: pad-between was 10.691% slower by mean and 11.482% slower by 5%-trimmed mean. The paired penalty was +170.640 ms with a 95% interval of +89.728 to +251.552 ms, with all 16 fully logged workload counters matching across 100 steps. The implementation removes the original data-movement contention, but the current image cannot run full-context inter-sequence padding through FlashAttention 2 and has no FA3, so the path falls back to cuDNN fused attention. Retain grouped/Flash for production until a competitive padding-capable backend is available; this commit keeps the cleaner generic API for review and future backend support. Signed-off-by: Desh Raj <r.desh26@gmail.com>
faea818 to
a88c9b6
Compare
for more information, see https://pre-commit.ci
Mixed-mask dispatch represents sequences owned by other policies as inter-sequence padding. FA3 preserves that layout contract, but its padding lanes are unspecified: focused Hopper testing observed NaNs in inactive forward outputs and tile-spill garbage in inactive dQ/dK/dV lanes. Build a sync-free mask from the physical cu_seqlens, sanitize each policy output with torch.where, and wrap Q/K/V in an identity-forward autograd guard that zeros only inactive gradient lanes. This keeps the pad_between_seqs design, avoids regrouping or copying tokens, and lets disjoint policy results be summed safely across FA2 and FA3. Validation: NRT H100 source-overlay run passed all 16 focused mixed-THD tests for FP16/BF16 forward and backward, pre-existing padding, cross attention, per-policy windows, CUDA graphs, and validation errors. Signed-off-by: Desh Raj <r.desh26@gmail.com>
Keep attn_mask_type_per_seq and window_size_per_mask_type invariant at the caller boundary while selecting the physical implementation inside DotProductAttention. Use inter-sequence padding only on SM90 when FlashAttention 3 is installed and enabled. Fall back to per-policy token compaction, scalar THD attention, and output restoration for FlashAttention 2 and other configurations. Preserve the uniform-policy scalar fast path and restrict CUDA graph coverage to the sync-free FA3 padding path. Add a runtime dispatch matrix covering architecture, FA3 availability, and backend environment controls. Validation: - NRT H100/FA3: 21 mixed-THD tests and 4 Megatron policy/API tests passed - IAD A100/FA2: 20 mixed-THD tests passed, 1 Hopper-only graph test skipped, and 4 Megatron policy/API tests passed - Installed-image five-step training smokes were bit-identical within FA3 across NRT/HEL and within FA2 across IAD/ORD; maximum cross-backend loss delta was 1.56e-5
|
@cyanguwa @KshitijLakhani I made the changes following @cyanguwa's suggestions. The main issue is that the
|
|
Thanks for the pictorial summary :) @KshitijLakhani will help guide you through the rest of the PR. Regarding the benchmarks, should we not expect more savings from |
I previously ran this comparison on H100: |
KshitijLakhani
left a comment
There was a problem hiding this comment.
General comments:
-
The new argument/feature currently appears to be exposed directly through
DotProductAttention; I do not see corresponding plumbing throughMultiheadAttentionorTransformerLayer. Would be good if you could add that too - I'm guessing we wouldn't necessarily want to restrict users of this feature to theDPAAPI only. Ideally, would be good if you could just plumb it in this PR, however, if you are in a rush, I am happy to have this addressed in a separate PR. Please add a TODO so that we do not forget, in case you plan to address it separately -
I might have missed this but if this PR does not explicitly reject CP for this policy based approach, we should. Users should no try to use it with CP. A very small / lightweight CP rejection test would help add confidence to this rejection code.
| mask_type, | ||
| policy["window_size"], | ||
| ) | ||
| policy_bottom_right_diagonal = bottom_right_diagonal |
There was a problem hiding this comment.
bottom_right_diagonal is stored internally per policy, but looks like it is derived from the global argument and mask type and ussers cannot specify it independently per policy. Is my understanding right ?
Now, this may be intentional, particularly because the causal mask names encode much of the alignment behavior. Still, since mask and sliding window are now policy-specific, could you please confirm whether bottom-right alignment can ever legitimately vary between policies. If so, it belongs in the policy object too.
There was a problem hiding this comment.
For our use cases right now, we don't need policy-specific variation in bottom_right_diagonal, but I can imagine in some cross-attention/local attention use cases it may be useful. I will include it as per-policy field in thd_attention_policies.
| interleave sits; must be -3 (e.g. ``bs3hd``) or -2 (e.g. ``bsh3d``, | ||
| Megatron-style). This is an explicit knob rather than shape inference, | ||
| since e.g. ``h == 3`` would make the shapes ambiguous. | ||
| attn_mask_type_and_window_size_per_seq_policies: Optional[List[Dict[str, Any]]], |
There was a problem hiding this comment.
Choose a more generic name like : thd_attention_policies or earlier suggested attn_policies_per_seq so that it is not perceived as a policy for swa and attn masks only
| are supplied as a one-dimensional, strictly ascending CUDA integer tensor; | ||
| all policy tensors must be disjoint and together contain every sequence | ||
| exactly once. A list may contain multiple policies with the same mask type |
There was a problem hiding this comment.
Are we validating/verifying these mentioned conditions in the comments anywhere in code?:
- Strictly ascending IDs within a policy.
- Duplicates within one policy.
There was a problem hiding this comment.
Since policy metadata is expected to be static, could we validate the sequence IDs once before CUDA graph capture and then treat them as immutable?
I'm thinking that for each policy, we should check that IDs are strictly ascending, and the sorted concatenation of all policy IDs should equal arange(batch_size). Now the issues is that these checks will synchronize when their result is converted to a Python boolean IIUC, but that should be acceptable as a one-time preparation/warm-up cost. They should not execute inside the captured forward path. A small validation step (or cached validation before capture though need to think a bit through this one's detils) may be the cleanest approach.
| attention_params_kwargs, | ||
| ) | ||
| padded_output = None | ||
| if padded_policies: |
There was a problem hiding this comment.
The routing currently treats padded-backend availability as a preference: if FA3 or Fused Attention can run the policy with pad_between_seqs=True, padded execution is always selected. This makes sense and I agree with it as an initial policy, but get_attention_backend() only determines backend eligibility for that representation; it does not compare its end-to-end performance against compacting and using FA2/FA4.
It is more of a what is supported call rather than which is more performant call.
So, I'm wondering, to give the users of this feature better guidance, could you please document that mixed THD dispatch is intentionally padded-first .
Users can however, indirectly force grouped execution by disabling FA3 and Fused Attention while leaving FA2/FA4 enabled, but those environment variables affect all attention calls. This is documentation/comment should give enough guidance to the user to maybe experiment the different routes padded and grouped, (assuming they have them available) and then if they find that our approach of choosing padded is less performant for their case they can force TE to use grouped via the env vars.
Note for the future: I have not done any benchamarking on this but @desh2608 if you do any benchmarking and we learn that grouped remains materially faster for important workloads, it may be worth providing a direct padded/grouped preference or override rather than relying solely on global env var backend controls.
There was a problem hiding this comment.
I had benchmarked both in my training setup, and the iteration times are as follows:
| Method | Attn. backend | Iteration time (ms) |
|---|---|---|
| Grouped | FA2 | 1669.9 |
| Grouped | FA3 | 1548.2 |
| Padded | FA3 | 1635.7 |
Given that grouped + FA3 seems faster, I will add an optional override so users can select this implementation.
| bottom_right_diagonal=policy["bottom_right_diagonal"], | ||
| pad_between_seqs=True, | ||
| ) | ||
| *_, available_backends = dpa_utils.get_attention_backend(padded_attention_params) |
There was a problem hiding this comment.
So seems like for the attention params, we have an uncache probe here, which is unlike what we do otherwise in DPA (see lines 2535 in this file)
It looks something like this:
if (
_attention_backends["attention_params"] is None
or attention_params != _attention_backends["attention_params"]
):
_partition_thd_mask_policies() calls get_attention_backend() directly for every policy at line 1359, bypassing the normal _attention_backends cache used by the usual forward path. The subsequent recursive self.forward() can then perform backend selection again when it executes that policy. Was this repeated selection intentional @desh2608 ?
I'm concerned this maybe fine initially, but could you measure the CPU overhead for the latest implementation ? If it is substantial/materical engouth , perhaps the policy probe results could be cached by AttentionParams or reused during execution ? Please evaluate this
There was a problem hiding this comment.
No this was an oversight. Fixed in 0ced9fc. The CPU overhead was ~200us per call.
| @@ -0,0 +1,582 @@ | |||
| # Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | |||
There was a problem hiding this comment.
Could the new tests reuse more of the existing attention test infrastructur? For e.g. DPA/config construction, THD input generation, backend forcing and comparison helpers?
I am less conflicted about whether the tests remain in a dedicated file or we find an easy/clean way to integrate into the test_attention file instead, however, since the feature now has enough cases to justify a separate file, I'm happy to consider that possibility. My main maintenance concern is avoiding duplicated
setup/reference machinery. Trying to focus on mainainability.
While you perform this restructure, please weight the possibility of just having this as a separate function/class in the fused attention test file itself if it relatively clean to do so, else stick wih a separate file and only address the re-use comment i have bove
There was a problem hiding this comment.
Updated to reuse the existing infrastructure in 9f01ef8. I kept the new tests in a separate file since there are many cases.
Signed-off-by: Desh Raj <r.desh26@gmail.com>
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
Added in 2dca008 |
3952732 to
0ced9fc
Compare
Added plumbing in 156069f |
|
|
||
|
|
||
| def _run_dot_product_attention( | ||
| def make_cu_seqlens(seqlens: torch.Tensor) -> torch.Tensor: |
There was a problem hiding this comment.
I extracted these into public methods so they can be re-used in test_mixed_thd_attention.py.
| make_dot_product_attention, | ||
| reset_rng_states, | ||
| run_dot_product_attention, | ||
| ) |
There was a problem hiding this comment.
We are now re-using the same setup as in test_attention.py. This file only contains cases specific to mixed attention.
Signed-off-by: Desh Raj <r.desh26@gmail.com>
|
/te-ci L0 L1 L2 |
Signed-off-by: Desh Raj <r.desh26@gmail.com>
…inimal Signed-off-by: Desh Raj <r.desh26@gmail.com>
|
@KshitijLakhani FYI one of the tests was failing on H100 due to a backend selection bug which is now fixed in 98f375f. |
| if ( | ||
| use_flash_attention | ||
| and (window_size[0] != -1 or window_size[1] not in [-1, 0]) | ||
| and not bottom_right_diagonal | ||
| and max_seqlen_q != max_seqlen_kv | ||
| ): | ||
| logger.debug( | ||
| "Disabling FlashAttention as it only supports sliding window with bottom right" | ||
| " diagonal alignment for cross-attention" | ||
| ) | ||
| use_flash_attention = False |
There was a problem hiding this comment.
This fix follows the existing convention of using max_seqlen_q != max_seqlen_kv for cross-attention-like cases. For variable-length THD, can individual Q/KV lengths differ while their global maxima are equal? @cyanguwa
If so, the selector cannot distinguish that case today. I believe that is a broader existing limitation rather than something this PR needs to solve, but it may be worth a follow-up test or issue.
Not blocking the PR on this for now
|
/te-ci L0 L1 L2 |
KshitijLakhani
left a comment
There was a problem hiding this comment.
LGTM !
Thanks for implementing this feature, Desh and taking it to the finish line :)
…radient The Lint job fails on this branch with dot_product_attention.py:243:4: C0116: Missing function or method docstring dot_product_attention.py:248:4: C0116: Missing function or method docstring _IdentityWithMaskedGradient came from NVIDIA#3274 and is byte-identical to main; the same two errors fail Lint on that PR's own branch (desh/mixed-thd-pr-minimal), which merged before the check went green, so this branch inherited a red Lint by merging main. Not introduced here, but it blocks this PR. Use the same `# pylint: disable=missing-function-docstring` the other autograd Functions in this package use (e.g. context_parallel.py) rather than inventing docstrings. Drop this commit if NVIDIA#3274 is fixed upstream first. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…3391) * feat: thread tanh logit softcapping through FlashAttention (FA2, opt-in FA3) Add a user `softcap` value (tanh logit softcapping, `softcap*tanh(x/softcap)`) to DotProductAttention so models like Gemma2 can run on the fused flash path instead of an unfused/FlexAttention kernel. - Add `softcap` to DotProductAttention (init+forward) and AttentionParams; thread it into the FA2 non-CP kwargs and all three context-parallel autograd functions (forward + ctx-saved backward). softcap=0.0 reproduces prior behavior. - get_attention_backend: when softcap != 0, disable FusedAttention/unfused and steer to FA2 -- disable FA3/FA4, and disable FA2 < 2.6.0 -- so the cap is never silently dropped (FA2 < 2.6.0) or hit at runtime as NotImplementedError (FA3/FA4). Also disable FA3 under context parallelism (its CP path hard-rejects nonzero softcap) so CP+softcap steers to FA2, which supports it, instead of crashing. - FA3 softcap opt-in: NVTE_FA3_SOFTCAP=1, Hopper (sm90) hd<=256, non-CP only, gated on a fail-closed signature probe (fa3_supports_softcap). Forward threads softcap into fa_3_optional_forward_kwargs; the existing Hopper autograd function carries it into backward automatically. Default off; unchanged behavior steers to FA2. - ONNX export: fail loudly (assert) rather than silently drop softcap -- export unconditionally force-selects UnfusedDotProductAttention, which has no softcap support, so this previously exported models with softcapping silently omitted. - Tests: test_softcap.py (FA2 fwd/bwd parity vs pure-PyTorch reference), wired into qa/L0_pytorch_unittest/test.sh. FA4 softcap opt-in is deliberately NOT included here -- see follow-up PR. On Blackwell (SM100), FA4's dedicated head_dim=256 forward kernel has no score_mod support at all (kernel constructor asserts `score_mod is None`), so there is currently no FA4 kernel path this could opt into; adding the scaffolding now would just be inert code with nothing to exercise. Addresses review findings: CP+FA3 softcap selection crash, ONNX silent drop, and the missing CI wiring for test_softcap.py. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: use raise instead of assert for the ONNX+softcap guard python -O / PYTHONOPTIMIZE strips assert statements, which would silently reopen the ONNX export softcap-drop bug the previous commit fixed (ONNX mode would again force-select UnfusedDotProductAttention with softcap silently omitted, with no error). Switch to an explicit if/raise ValueError, which survives optimized execution. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci (reapplied after a force-push rebase clobbered pre-commit.ci's original 19a21eb commit; same content, restored by hand) Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * refactor: move softcap reference into UnfusedDotProductAttention and fold test into test_attention.py UnfusedDotProductAttention now applies softcap * tanh(scores / softcap) to the already-scaled logits, matching how FlashAttention folds softmax_scale into its tanh argument, so it can serve as the softcap reference backend. Backend selection therefore no longer disqualifies unfused attention for softcap, and the ONNX-export guard is dropped since the export path force-selects unfused and torch.tanh is exportable. test_softcap.py is replaced by a model_configs_softcap dict and test_dpa_softcap in test_attention.py, which reuses test_dot_product_attention for backend sweeping. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): gate FA3 softcap on existing NVTE_FLASH_ATTN_V3 Drop the redundant NVTE_FA3_SOFTCAP opt-in. `use_flash_attention_3` already derives from NVTE_FLASH_ATTN_V3, so the existing flag governs the FA3 softcap path and NVTE_FLASH_ATTN_V3=0 disables it. Correctness stays established by the build-capability probe, head_dim <= 256, and the non-CP requirement. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): disable FlashAttention 4 for softcap FA4 exposes no softcap kwarg and its head_dim=256 kernel asserts score_mod is None, so there is no kernel to route the cap through. The FA4 call path in backends.py passes no softcap, so an FA4 selection with a nonzero softcap silently dropped the cap instead of failing closed. NVTE_FLASH_ATTN_V4 defaults to enabled, so this was reachable on SM100+ with flash-attn v4 installed and no context parallelism. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): disable FlashAttention 2 for softcap with dropout flash-attn rejects a nonzero softcap combined with nonzero dropout at dispatch: "Softcapping does not support dropout for now" in csrc/flash_attn/flash_api.cpp, present in mha_fwd and mha_varlen_fwd from v2.6.0 (the earliest version TE allows softcap on) onwards. Backend selection did not model this, so a softcap + attention-dropout config passed selection, routed to FA2, and crashed inside flash-attn. Dropout only reaches the kernel while training, since backends.py passes `self.attention_dropout if self.training else 0.0`, so the gate is on `attention_dropout != 0.0 and is_training` to avoid blocking valid inference configs. UnfusedDotProductAttention supports both softcap and dropout and stays available, so this steers rather than hard-fails. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * test: restore softcap dQ/dK/dV parity in the shared DPA harness test_dot_product_attention forced is_training=False whenever FusedAttention could not train a config, so that backends only available for inference could still be compared. softcap always disables FusedAttention, so test_dpa_softcap silently degraded to a forward-only comparison and the PR's backward-parity claim -- the FA2 softcap backward kernel included -- went untested. Add fwd_only_without_fused_attn (default True, so every other caller is byte-for-byte unchanged) and opt test_dpa_softcap out, which pairs FlashAttention against UnfusedDotProductAttention with is_training=True and restores the dgrad comparison. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * test: add softcap no-op and closed-form reference coverage Two gaps remained after folding test_softcap.py into test_attention.py. softcap=0.0 no-op: every model_configs_softcap entry uses a nonzero cap, so nothing asserted the backward-compatibility claim. The half that the PR actually changed is backend selection, and a filter that fired at 0.0 would silently remove FusedAttention and FA4 from other tests rather than fail one. test_dpa_softcap_zero_backend_selection asserts FusedAttention survives softcap=0.0 and is disabled by a nonzero cap. Unfused coverage and tanh's nonlinear region: test_dpa_softcap needs two TE backends, so it skips entirely without flash-attn even though UnfusedDotProductAttention now implements softcap and is the reference for everything else. It also cannot detect a dropped cap at all: 0.1 * randn inputs put the logits at O(1e-2), where the reference output moves by 9e-9 at cap=50 and 2e-4 at cap=0.01. test_dpa_softcap_vs_reference compares forward and dQ/dK/dV against a pure-PyTorch oracle one backend at a time, so it runs with unfused alone, and uses randn inputs so the cap moves the output by O(1). An assertion on that displacement keeps the test from going vacuous if the config drifts. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): align CP autograd backward arity with the softcap forward input Threading `softcap` through the three context-parallel autograd functions added a forward input to each without adding the matching gradient slot to the corresponding backward return tuple, leaving every CP backward one gradient short of its forward inputs. Because `softcap` sits mid-signature, the omission also shifted every later slot in AttnFuncWithCPAndQKVOA2A: `d_softmax_offset` was being returned in `softmax_type`'s position. Insert the missing slot at the `softcap` position in all three tuples. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * test(pytorch): cover context parallelism with softcap No test exercised CP together with softcap, which is why a backward that returned one gradient fewer than its forward inputs went unnoticed in all three CP autograd functions. Thread softcap through the CP runner so it reaches DotProductAttention, and add one case per CP autograd function -- p2p, all_gather and a2a -- checking the softcapped forward and dgrad against the non-CP reference. The cap sits in tanh's nonlinear region so a path that dropped it diverges rather than matching a numerically linear reference. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): apply softcap before the additive bias, matching FlashAttention UnfusedDotProductAttention applied the tanh cap after adding post_scale_bias / ALiBi, computing cap(scale*QK + bias). FlashAttention-2 computes cap(scale*QK) + bias: its kernel softcaps immediately after the QK^T gemm and only then adds ALiBi, and it pre-divides alibi_slope by scale_softmax -- which softcapping sets to `softcap` -- so the bias deliberately lands outside the tanh (csrc/flash_attn/src/flash_fwd_kernel.h, mask.h, flash_api.cpp). ALiBi is the one bias type flash supports, so with softcap + ALiBi the unfused and flash paths returned different numerics depending only on whether a suitable flash-attn was installed. Defer the additive bias until after the cap so the two agree. pre_scale_bias is folded in before the scaling by construction and stays inside the cap; flash does not support it. softcap = 0.0 remains a bit-exact no-op for every bias type. Add two tests, both forcing UnfusedDotProductAttention: - test_dpa_softcap_bias_ordering pins cap(scores) + bias against cap(scores + bias), using post_scale_bias to drive the same branch ALiBi uses without needing slope machinery in the reference. - test_dpa_softcap_qk_layer_scaling covers softcap under NVTE_APPLY_QK_LAYER_SCALING, where the cap must be divided by layer_number; omitting that leaves an effective cap of softcap * layer_number. Both carry anti-vacuity asserts, and both were verified by mutation on an H100: reintroducing either bug makes the corresponding test fail, and the existing softcap suite still passes. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix(test): skip the softcap no-op check when FusedAttention is unavailable test_dpa_softcap_zero_backend_selection asserted that FusedAttention is selectable at softcap=0.0. Whether it is available at all depends on the arch and on NVTE_ALLOW_NONDETERMINISTIC_ALGO, not on softcap: the A100 and L40 CI jobs fail the assert in their deterministic pass, where cuDNN offers no fused backend for this config, while the same test passes on H100 and B200. The test is about the softcap filter, so make the availability half a skip. The meaningful direction -- a nonzero softcap must disable FusedAttention -- still runs wherever a fused backend exists, and skipping keeps the comparison from being silently vacuous where one does not. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(lint): silence missing-function-docstring on _IdentityWithMaskedGradient The Lint job fails on this branch with dot_product_attention.py:243:4: C0116: Missing function or method docstring dot_product_attention.py:248:4: C0116: Missing function or method docstring _IdentityWithMaskedGradient came from #3274 and is byte-identical to main; the same two errors fail Lint on that PR's own branch (desh/mixed-thd-pr-minimal), which merged before the check went green, so this branch inherited a red Lint by merging main. Not introduced here, but it blocks this PR. Use the same `# pylint: disable=missing-function-docstring` the other autograd Functions in this package use (e.g. context_parallel.py) rather than inventing docstrings. Drop this commit if #3274 is fixed upstream first. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat: expose softcap on MultiheadAttention and TransformerLayer; trim comments Review feedback from #3391. Thread softcap through MultiheadAttention and TransformerLayer, following the window_size pattern: a constructor argument stored on the module and a forward argument that falls back to it. TransformerLayer passes softcap via common_attention_kwargs, so it reaches cross-attention as well as self-attention, matching how softmax_type (also not mask-specific) is handled; scoping it to self-attention would silently leave decoder cross-attention uncapped. Resolution sits outside the thd_attention_policies branch at both levels, since softcap is not mask-specific. Drop "only supported by the FlashAttention and UnfusedDotProductAttention backends" from the softcap docstrings. It is inaccurate, since support depends on the FlashAttention version, and get_attention_backend() is the single place that should describe backend eligibility. The same wording appeared in the DotProductAttention class and forward docstrings, so all three now describe only what softcap does. Shorten the softcap comment in UnfusedDotProductAttention, keeping why the cap precedes the additive bias and why it is divided by layer_number, as each of those was a real bug. Remove the fail-loud block comment in the FA3 branch, whose selection criteria get_attention_backend() already documents, and keep a single line noting that the FA3 entry points are autograd functions and so the forward kwarg drives the backward too. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: append softcap to the MHA and TransformerLayer forward signatures softcap was inserted mid-signature in MultiheadAttention.forward and TransformerLayer.forward, next to the other attention arguments. That shifts every parameter after it, so an external caller passing encoder_output or is_first_microbatch positionally would silently bind it to softcap instead. Both accept arbitrary objects, so it would be a wrong answer rather than a TypeError. Nothing in this repo calls either forward with enough positional arguments to hit it, but both classes are public API. Move softcap to the end of both forward signatures. Diffing against main confirms no existing parameter changes index in either. The constructors are unaffected and keep softcap grouped with window_size and bottom_right_diagonal, since it sits past every positional tuple used to construct these modules. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test: consolidate the softcap tests Review feedback from #3391. Cut model_configs_softcap from six configs to two: softcap_1_0 for a high cap through flash_attn_func, and softcap_3_1 with padding_causal for a low cap through flash_attn_varlen_func. Fold model_configs_softcap_reference from three to two by merging GQA into the causal config, since GQA is orthogonal to softcapping. Merge test_dpa_softcap_vs_reference, test_dpa_softcap_bias_ordering and test_dpa_softcap_qk_layer_scaling into one test parametrized over {plain, bias_outside_cap, qk_layer_scaling}. A helper returns the DPA kwargs, the forward kwargs and a right and a wrong reference closure per variant, so the shared work of forcing a backend, building inputs and asserting the two references differ by more than the tolerance happens once. The bias variant reuses _softcap_reference_attention through new bias and cap_includes_bias arguments rather than duplicating its GQA and causal handling. Both mutation signals are preserved. The special variants run on softcap_ref_1_0, the same shape the original margins were measured on, so capping the bias still separates the two references by about 0.98 and dropping the cap / layer_number division by about 0.44, against a threshold of 0.20. layer_number is hoisted to _SOFTCAP_QK_LAYER_NUMBER with a note that 3 is too small, since that value is load-bearing and would otherwise look arbitrary. Backward stays on the plain variant only, matching the previous coverage. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test: assert TransformerLayer forwards softcap to both attention modules Adds test_transformer_layer_softcap_plumbing. It builds a decoder TransformerLayer with a softcap, hooks both self_attention.core_attention and inter_attention.core_attention with a forward pre-hook, and asserts each sees the value, once from the constructor and once from a forward override. Only arrival is checked; the numerics are covered by the DotProductAttention tests. Cross-attention is the half worth asserting. It is reached through a separate call site from self-attention, so a refactor can drop the cap there while self-attention keeps working, and nothing else in the suite would notice. Main restructured both forward methods during this branch's life, so that is a live risk rather than a hypothetical one. Writing the test showed that passing softcap through common_attention_kwargs was not merely redundant but harmful: it pre-set each MultiheadAttention's self.softcap, so deleting the cross-attention pass-through still produced the right answer on the constructor path and the assertion could not fail. Removing that entry makes both assertions catch the regression, and leaves softcap matching how window_size is threaded, stored on self and passed per call rather than at construction. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test: set explicit backend state in the softcap plumbing test The test inherited NVTE_FLASH_ATTN / NVTE_FUSED_ATTN / NVTE_UNFUSED_ATTN from whichever softcap test ran before it, since none of them restore those vars. A nonzero cap also drops FusedAttention and FA4 in the backend filter, so a leftover NVTE_UNFUSED_ATTN=0 could leave no eligible backend at all and the forward would raise "No dot product attention backend is available" rather than fail an assertion. The outcome also depended on which parametrization of the preceding test happened to run last. Set the three variables explicitly, matching the convention of the other tests in this file, leaving flash and unfused both enabled so at least one backend is available with or without flash-attn. The assertions stay backend agnostic because the hook fires on DotProductAttention itself. Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(pytorch): tighten softcap comments and correct the FA4 attribution Halve the comment volume added to backends.py and utils.py, keeping only the facts that are not inferable from the code: that FA2 adds ALiBi outside the cap, and why the cap is divided by layer_number. Which backend supports what is already expressed by get_attention_backend and its debug messages. Also correct two inaccuracies found while auditing the surviving text. FA4 does implement softcap on both entry points TE calls, forward and backward, so it is disqualified because TE does not plumb the cap to it, not because the library lacks it; the log message said otherwise. And the FA3 signature probe detects whether the installed release exposes the kwarg at all, not whether the build set FLASHATTENTION_DISABLE_SOFTCAP, which still exposes it and rejects a nonzero cap at dispatch. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): probe softcap on all three FA3 entry points softcap is injected into fa_3_optional_forward_kwargs without regard to which entry point was selected, so the probe should cover every function the cap can reach. flash_attn_with_kvcache is the one chosen when inference_params is set, and it was validated only by proxy through the other two. No shipped FA3 build changes behaviour: all three entry points gained softcap in 2.7.3/hopper, which is TE's documented FA3 floor. Before that none of them had it. The symbol is already imported and None-guarded, so the probe cannot fire on an uninstalled FA3. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * test: exercise softcap at head_dim 128, not only 64 Cutting model_configs_softcap to two configs dropped head_dim 128 as a side effect, leaving every softcap config at 64. FA2 and FA3 compile a separate softcap kernel per head_dim bucket, and above 128 FA2 additionally forces the non-even-MN predicated path, so a bug in those kernels is invisible at 64. Widen the existing padding config instead of adding a third, so the count stays at two. Neither justification for the pair changes: head_dim plays no part in the flash_attn_func vs flash_attn_varlen_func dispatch, and the 0.01 cap rationale is head_dim invariant because softmax_scale cancels the sqrt(d) growth of the dot product. 128 rather than 256 because get_attention_backend disables FA3 for deterministic backward at head_dim >= 256, which would leave only UnfusedDotProductAttention and skip the comparison in the NVTE_ALLOW_NONDETERMINISTIC_ALGO=0 CI pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * test: restore backend env vars in the softcap plumbing test The test set NVTE_FLASH_ATTN, NVTE_FUSED_ATTN and NVTE_UNFUSED_ATTN and never restored them, leaking NVTE_FUSED_ATTN=0 into every test that ran after it. Its own comment names that hazard as the reason it sets them explicitly, then reproduces it. Wrap the body in try/finally, restore the previous values, and invalidate the backend selection cache on the way out. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): reject a negative softcap instead of diverging silently tanh is odd, so UnfusedDotProductAttention's `cap * tanh(x / cap)` gives a bit-identical result for -c and +c, i.e. it caps at the absolute value. FlashAttention only enables capping under `softcap > 0.0`, so it applies no cap at all. get_attention_backend gates on `softcap != 0.0`, so a negative value passed every filter and the two backends silently disagreed, which is the exact failure mode the rest of this PR exists to prevent. Raise on a negative cap where softcap is resolved, which is the choke point every caller reaches, including MultiheadAttention and TransformerLayer. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * fix(pytorch): reject a non-finite softcap as well as a negative one The existing guard exists to stop the backends disagreeing silently about a cap they cannot all honour, but NaN slipped through it and caused exactly that disagreement: UnfusedDotProductAttention computes cap * tanh(x / cap) and returns NaN for every score, while FA2 and FA3 gate their kernels on softcap > 0.0, which is false for NaN, so they drop the cap and return ordinary uncapped attention. Infinity produces NaN on every backend instead, which at least fails loudly. Neither is a legitimate way to spell a disabled cap. The limit of c * tanh(x / c) as c grows is the identity, but evaluated at infinity it is inf * 0, which is NaN, so the intuition does not survive floating point. Fold both into the existing check with math.isfinite, matching how ScaledTanhSReLU and ScaledSiTUGLU validate the same shape of parameter. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> * test: pin the softcap validity guard The guard had no coverage, for either the negative case or the non-finite one. Parametrised over -1.0, inf and nan, exercising both the constructor value and the forward override, since both resolve on the same path. Mirrors test_scaled_tanh_srelu_rejects_bad_clamp_scale, which pins the same shape of check on ScaledTanhSReLU. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> --------- Signed-off-by: Nitin Vegesna <nvegesna@nvidia.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Charlene Yang <8636796+cyanguwa@users.noreply.github.com>


Description
Add per-sequence attention policies to packed THD attention.
A scalar
attn_mask_type,window_size, andbottom_right_diagonalapply one policy to an entire packed invocation. Mixed offline/causal training instead needs individual packed sequences to use different policies while preserving a single caller-facing API.The new
thd_attention_policiesAPI accepts an ordered list of complete policies:Every policy must contain
sequence_ids,mask_type, andwindow_size.bottom_right_diagonalis optional and falls back to the forward-level or module-level setting. Mask types with explicit causal alignment retain their existing semantics:padding_causalforces top-left alignment andpadding_causal_bottom_rightforces bottom-right alignment.Sequence IDs are one-dimensional, strictly ascending CUDA
int32orint64tensors. The policy tensors must be disjoint and together cover every packed sequence exactly once. Repeated mask types are allowed, so separate sequence subsets can use the same mask with different windows or diagonal alignment. Policy IDs are validated once before CUDA graph capture and then treated as immutable.The mixed-policy argument is mutually exclusive with scalar
attn_mask_typeandwindow_sizearguments.API accessibility
Both mixed-policy options are exposed at every relevant PyTorch layer:
thd_attention_policiesthd_attention_policy_dispatchCallers using
TransformerLayerorMultiheadAttentiontherefore have the same automatic/grouped control as direct DPA callers.Runtime dispatch
thd_attention_policy_dispatch="auto"is intentionally padded-first. For each nonempty policy, Transformer Engine queries its ordinary backend selector with the complete runtimeAttentionParamsandpad_between_seqs=True:thd_attention_policy_dispatch="grouped"explicitly compacts every policy and bypasses padded-backend probing. The override also applies to a uniform one-policy batch; the scalar fast path does not bypass the requested dispatch.Inter-sequence-padding representation
The padding path:
pad_between_seqs=True.Grouped-compaction representation
The grouped path:
pad_between_seqs=False.Backend-selection caching
Mixed policies alternate among a small set of
AttentionParams. Their complete backend-selection results are stored in a bounded cache and reused by the recursive scalar attention calls. The cache accounts for backend-control environment state and is invalidated when ordinary DPA backend selection is marked for refresh.In a controlled same-node H100 microbenchmark, the steady-state selector calls per mixed forward changed from 4 to 0 for automatic dispatch and from 2 to 0 for grouped dispatch. The directly measured selector CPU time removed was 242.0 us/forward and 169.6 us/forward, respectively. Total host submission time decreased by 170.6 us (8.1%) for automatic dispatch and 109.5 us (5.3%) for grouped dispatch. These are DPA microbenchmark results, not full-model throughput estimates.
Supported scope
The new API supports:
MultiheadAttention, andTransformerLayercallers.It is currently restricted to padding mask types and does not support:
Type of change
Validation
Focused tests cover:
The A100 skip is the Hopper/FA3-only CUDA graph case. Python compilation, the repository's Black configuration, and whitespace checks pass for all changed files.
End-to-end 4B ASR profile
A dedicated one-node/eight-GPU profile ran the 4B/A770M model on ASR-only data for 100 optimizer steps per mode. All-causal, all-full-attention, and 50%-causal modes ran sequentially in the same exclusive allocation on each architecture. The table reports the steady-state mean over iterations 7-100 (
n=94).All-causal and all-full attention are within 1% end to end on both systems. The heterogeneous path is slower because policy grouping and multiple backend invocations are paid in each audio layer. Since A100 and H100 used different cluster-local containers, the cross-architecture ratio should not be interpreted as a pure silicon comparison.
Checklist
The focused GPU suites, backend-selection tests, end-to-end 4B profiles, Python compilation, formatting, and whitespace checks pass as described above.